package com.haizhi.crm.sys.shiro;

import com.haizhi.crm.sys.bean.User;
import com.haizhi.crm.sys.dao.UserDao;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserDao userDao;

    public UserRealm(UserCredentialsMatcher matcher) {
        super(matcher);
    }

    // 用户权限验证
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    // 用户登录验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        User user = userDao.findByName(username);
        if (user == null) {
            throw new AuthenticationException("用户[" + username + "]不存在");
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }
}
